package com.ahs.algorithm;

import org.junit.jupiter.api.Test;

import java.util.Arrays;

/**
 * @author riven zhang
 * @since 2021/9/2 16:59
 */
public class MergeArrays {

    private int[] merge(int[] a, int[] b) {
        int[] num = new int[a.length + b.length];
        int m = 0, n = 0;

        while (m < a.length && n < b.length) {
            if (a[m] > b[n]) {
                num[m + n] = b[n];
                n++; // n会越界吗？
            } else {
                num[m + n] = a[m];
                m++;
            }
        }
        if (m == a.length) {
            System.arraycopy(b, n, num, m + n, num.length - (m + n));
        }
        if (n == b.length) {
            System.arraycopy(a, m, num, m + n, num.length - (m + n));
        }

        return num;
    }

    @Test
    void test() {
        int[] a = {1, 3, 5, 7, 9};
        int[] b = {2, 4, 6, 8};
        int[] merge = merge(a, b);
        System.out.println(Arrays.toString(merge));
    }
}
